package com.vq3.digitalizationsoftwareintegrates.Servlet.UtilsCenter;


import com.vq3.digitalizationsoftwareintegrates.Entity.Info.ResultInfo;
import com.vq3.digitalizationsoftwareintegrates.Entity.UtilsCenter.UtilsCenterTbEntity;
import com.vq3.digitalizationsoftwareintegrates.Service.UtilsCenter.UtilsCenterFusionService;
import com.vq3.digitalizationsoftwareintegrates.Utils.ImageUtil.QRCodeUtil;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.Impl.PackagedDataImpl;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.PackagedData;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("UtilsCenter")
public class UtilsCenterServlet {
    @Resource
    UtilsCenterFusionService utilsCenterFusionService;

    @PostMapping("generate")
    public String generateV2(String content, HttpServletResponse servletResponse) throws IOException {
        BufferedImage codeToOutputStream = null;

        PackagedData packagedData = new PackagedDataImpl();
        try {
            codeToOutputStream = QRCodeUtil.createCodeToOutputStream(content, servletResponse.getOutputStream());

        }catch (Exception e){
            e.printStackTrace();
        }

        if (codeToOutputStream != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(codeToOutputStream, "png", stream);

            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(stream.toByteArray());

        }else {
            return null;
        }

    }

    @RequestMapping("getUtils")
    public void getUtils(HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<UtilsCenterTbEntity> utilsCenterTbEntities = utilsCenterFusionService.getUtils();
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setFlag(true);
        resultInfo.setData(utilsCenterTbEntities);
        packagedData.writeValue(resultInfo,response);
    }
}
